package com.sea.base.vm

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Author: Wu Chang
 *
 * Date: 2024/1/30 11:58
 */
class SingleLiveData<T>: MutableLiveData<T>() {

    private val mPending = AtomicBoolean(false)

    private var setValueTime = 0L

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner) {
            if (System.currentTimeMillis() - setValueTime < 200) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(it)
                }
            }
        }
    }

    override fun setValue(value: T?) {
        mPending.set(true)
        setValueTime = System.currentTimeMillis()
        super.setValue(value)
    }
}